# -*- coding:utf-8 -*-
# @File    : initializePremise.py
# **************************
import logging
import jsonpath
import time
import json,re,ast
import os
from json import JSONDecodeError
from config import PAGE_DIR, PROJECT_NAME, API_CONFIG
from config import *
from comm.unit import apiSend, readRelevance, replaceRelevance,authentication
from comm.utils import readYaml,randomly
from comm.unit.cacheData import *
from comm.unit.apiSend import send_request


def read_json(summary, json_obj, case_path):
    """
    校验内容读取
    :param summary: 用例名称
    :param json_obj: json文件或数据对象
    :param case_path: case路径
    :return:
    """
    if not json_obj:
        return None
    if isinstance(json_obj, dict):
        return json_obj
    else:
        try:
            # 读取json文件指定用例数据
            print("--------", case_path + '/' + json_obj)
            with open(case_path + '/' + json_obj, "r", encoding="utf-8") as js:
                data_list = json.load(js)
                for data in data_list:
                    if data['summary'] == summary:
                        return data['body']
        except FileNotFoundError:
            raise Exception("用例关联文件不存在\n文件路径： %s" % json_obj)
        except JSONDecodeError:
            raise Exception("用例关联的文件有误\n文件路径： %s" % json_obj)


def init_premise(test_info, case_data, case_path):
    """用例前提条件执行，提取关键值[暂时废弃该方法，该方法不支持多个前置条件，目前使用init_premise_new]

    :param test_info: 测试信息
    :param case_data: 用例数据
    :param case_path: 用例路径
    :return:
    """

    # 获取项目公共关联值
    aconfig = readYaml.read_yaml_data(API_CONFIG)
    run_evn = RC["run_evn"]
    __relevance = aconfig[PROJECT_NAME][run_evn]
    # 处理测试信息
    if "${" in test_info["address"]:  # 如果url地址中有需要替换的前置变量进入以下逻辑进行替换
        cache_name = case_path.replace(" ", "").split('page')[0] + 'page' + test_info["premise"]
        data = cache.get(cache_name)
        if not isinstance(data, dict):
            data = json.loads(data)
        test_info['address'] = readRelevance.get_addr_relevance(data, test_info['address'], __relevance)
    test_info = replaceRelevance.replace(test_info, __relevance)
    logging.debug("测试信息处理结果：{}".format(test_info))
    # 处理Cookies
    if test_info['cookies']:
        cookies = aconfig[PROJECT_NAME]['cookies']
        logging.debug("请求Cookies处理结果：{}".format(cookies))

    # 判断是否存在前置接口
    pre_case_path = test_info["premise"]
    if pre_case_path:
        print("lalapre_case_path:", pre_case_path)
        # 获取前置接口用例
        logging.info("获取前置接口测试用例：{}".format(pre_case_path))
        pre_case_yaml = PAGE_DIR + pre_case_path
        pre_case_path = os.path.dirname(pre_case_yaml)
        pre_case_dict = readYaml.read_yaml_data(pre_case_yaml)
        pre_test_info = pre_case_dict['test_info']
        pre_case_data = pre_case_dict['test_case'][0]
        # 判断前置接口是否也存在前置接口
        if pre_test_info["premise"]:
            init_premise(pre_test_info, pre_case_data, pre_case_path)
        if RC['case_switch'] == 0:  # 用例运行模式为场景用例不单独立执行前置
            pre_path_list = [i for i in test_info["premise"].split('/') if i != '']
            if pre_path_list[0] in case_path:
                pre_path, f = os.path.split(case_path)
                pre_file_path = os.path.join(pre_path, pre_path_list[1])
            else:
                _pre_path, f = os.path.split(case_path)
                pre_path = '/'.join(_pre_path.split('/').pop())
                pre_file_path = os.path.join(pre_path, pre_case_path)
            # 从缓存的前置接口返回值中替换变量
            case_data = init_premise_from_cache(case_data, pre_file_path, case_path, __relevance)

        for i in range(3):
            # 处理前置接口测试信息
            pre_test_info = replaceRelevance.replace(pre_test_info, __relevance)
            logging.debug("测试信息处理结果：{}".format(pre_test_info))
            # 处理前置接口Cookies
            if pre_test_info['cookies']:
                cookies = aconfig[PROJECT_NAME]['cookies']
                logging.debug("请求Cookies处理结果：{}".format(cookies))

            # 处理前置接口入参：获取入参-替换关联值-发送请求
            pre_parameter = read_json(pre_case_data['summary'], pre_case_data['parameter'], pre_case_path)
            pre_parameter = replaceRelevance.replace(pre_parameter, __relevance)
            pre_case_data['parameter'] = pre_parameter
            logging.debug("请求参数处理结果：{}".format(pre_parameter))
            logging.info("执行前置接口测试用例：{}".format(pre_test_info))
            code, data = apiSend.send_request(pre_test_info, pre_case_data, case_path)

            # 检查接口是否调用成功
            if data:

                # 处理当前接口入参：获取入参-获取关联值-替换关联值
                parameter = read_json(case_data['summary'], case_data['parameter'], case_path)
                __relevance = readRelevance.get_relevance(data, parameter, __relevance)
                parameter = replaceRelevance.replace(parameter, __relevance)
                case_data['parameter'] = parameter
                logging.debug("请求参数处理结果：{}".format(parameter))

                # # 获取当前接口期望结果：获取期望结果-获取关联值-替换关联值
                # expected_rs = read_json(case_data['summary'], case_data['check_body']['expected_result'], case_path)
                # parameter['data'] = data
                # __relevance = readRelevance.get_relevance(parameter, expected_rs, __relevance)
                # expected_rs = replaceRelevance.replace(expected_rs, __relevance)
                # case_data['check_body']['expected_result'] = expected_rs
                # logging.clueCheck("期望返回处理结果：{}".format(case_data))
                break
            else:
                time.sleep(1)
                logging.error("前置接口请求失败！等待1秒后重试！")
        else:
            logging.info("前置接口请求失败！尝试三次失败！")
            raise Exception("获取前置接口关联数据失败！")
    else:
        # 处理当前接口入参：获取入参-获取关联值-替换关联值
        if case_data['parameter'] == False:
            case_data['parameter'] = None
        else:
            parameter = read_json(case_data['summary'], case_data['parameter'], case_path)
            parameter = replaceRelevance.replace(parameter, __relevance)
            case_data['parameter'] = parameter
            logging.debug("请求参数处理结果：{}".format(parameter))

        # 获取当前接口期望结果：获取期望结果-获取关联值-替换关联值
        if case_data['check_body']['check_type'] == "check_string":
            expected_rs = str(case_data['check_body']['expected_result'])
            case_data['check_body']['expected_result'] = expected_rs
            logging.debug("期望返回处理结果：{}".format(expected_rs))
        else:
            expected_rs = read_json(case_data['summary'], case_data['check_body']['expected_result'], case_path)
            __relevance = readRelevance.get_relevance(parameter, expected_rs, __relevance)
            expected_rs = replaceRelevance.replace(expected_rs, __relevance)
            case_data['check_body']['expected_result'] = expected_rs
            logging.debug("期望返回处理结果：{}".format(case_data))

    logging.debug("lalalalala：{},第二个{}".format(test_info, case_data))
    return test_info, case_data



def init_premise_new(test_info, case_data, case_path):
    """用例前提条件执行，提取关键值,支持多个前置条件的接口
    :param test_info: 测试信息
    :param case_data: 用例数据
    :param case_path: 用例路径
    :return:
    """

    # 获取项目公共关联值
    aconfig = readYaml.read_yaml_data(API_CONFIG)
    run_evn = RC["run_evn"]
    __relevance = aconfig[PROJECT_NAME][run_evn]

    if "${" in str(test_info["address"]):  # 如果url地址中有需要替换的前置变量进入以下逻辑进行替换
        for _k,_v in test_info['premise'].items():
            cache_name = case_path.replace(" ", "").split('page')[0] + 'page'+'/' + _k
            # if pre_test_info["premise"]:
            #     test_info,case_data = init_premise_new(pre_test_info, pre_case_data, cache_name)
            data = cache.get(cache_name)
            if data == None:
                _casedata = readYaml.read_yaml_data(cache_name)
                pre_test_info = _casedata['test_info']
                pre_case_data = _casedata['test_case'][0]
                code, data = apiSend.send_request(pre_test_info, pre_case_data, cache_name)
            logging.debug("这个data是个啥:{}".format(data))
            if not isinstance(data, dict):
                data = json.loads(data)
            test_info['address'] = readRelevance.get_address_relevance(data, test_info['address'], __relevance)
            return test_info, case_data
    # test_info = replaceRelevance.replace(test_info, __relevance)
    logging.debug("测试信息处理结果：{}".format(test_info))
    # 处理Cookies
    if test_info['cookies']:
        cookies = aconfig[PROJECT_NAME]['cookies']
        logging.debug("请求Cookies处理结果：{}".format(cookies))

    # 判断是否存在前置接口
    pre_case_path = test_info["premise"]
    if pre_case_path :
        for k,va in pre_case_path.items(): #k,va前置路径和对应的待获取的字段名称
            if not isinstance(va,list): # 前置条件接口只有一个字段变量
                if '[' in str(va):
                    v = str(va).split('[')[0]
                else:
                    v = va
                # 处理测试信息
                logging.debug("获取前置条件用例：{}中的字段:{}".format(k,v))
                pre_case_yaml = PAGE_DIR+"/" + str(k)
                pre_case_path = os.path.dirname(pre_case_yaml)
                pre_case_dict = readYaml.read_yaml_data(pre_case_yaml)
                pre_test_info = pre_case_dict['test_info']
                pre_case_data = pre_case_dict['test_case'][0]
                # if pre_test_info["premise"]:
                #     cache_data = cache.get(str(k).replace("\\", "/"))
                #     if cache_data != None:
                #         pass
                #     else:
                #         test_info, case_data = init_premise_new(pre_test_info, pre_case_data, pre_case_path)

                if RC['case_switch'] == 0:  # 用例运行模式为场景用例不单独执行前置
                    pre_path_list = [i for i in pre_case_yaml.replace('\\','/').split('/') if i != '' and '.yaml' not in i ]
                    case_path_list = [i for i in case_path.split('/') if i != ''  and '.yaml' not in i]
                    if pre_path_list == case_path_list: #对比前置条件用例路径与本用例路径是否在同一目录下
                        pre_file_path = pre_case_yaml
                    else:
                        _pre_path, f = os.path.split(case_path)
                        pre_path = '/'.join(_pre_path.split('/').pop())
                        pre_file_path = os.path.join(pre_path, '\\'+str(k))
                    # 从缓存的前置接口返回值中替换变量
                    if "self" in va:
                        pre_test_info, pre_case_data = init_premise_new(pre_test_info, pre_case_data, pre_file_path)
                        apiSend.send_request(pre_test_info, pre_case_data, pre_file_path)
                        return test_info, case_data
                    my_data = init_premise_from_cache_new(case_data, pre_file_path, va, k)
                    if not my_data:
                        pre_test_info, pre_case_data = init_premise_new(pre_test_info, pre_case_data, pre_file_path)
                        code, data = apiSend.send_request(pre_test_info, pre_case_data, pre_file_path)
                        # test_info, case_data = init_premise_new(test_info, case_data, case_path)
                        if data:
                            # 处理当前接口入参：获取入参-获取关联值-替换关联值
                            var = {}
                            _values = readRelevance.getvalue(data, v, [])
                            if '[' in str(va):
                                n = int(str(va).split('[')[1].replace(']','').replace(" ", ""))
                                if str(n)+']}' in str(case_data['parameter']):
                                    var[va] = _values[n]
                                else:
                                    var[v] = _values[n]
                                # var[v] = _values[n]
                            else:
                                if var[v] == None:
                                    break
                                var[v] = _values[0]  # 取第一个最早出现的字段

                            # var[v] = _values[0]  # 取第一个最早出现的字段
                            logging.debug("获取关键字var：{}".format(var))
                            # parameter = read_json(case_data['summary'], case_data['parameter'], post_case_yaml)

                            case_data['parameter'] = replaceRelevance.replace_relevance_new(case_data['parameter'], var)
                        else:
                            time.sleep(1)
                            logging.error("前置接口请求失败！等待1秒后重试！")
                        # test_info, case_data = init_premise_new(pre_test_info, pre_case_data, pre_file_path)  #递归跑前置接口并缓存接口信息
                    else:
                        case_data = my_data #case_data取缓存中替换后的参数
                    #这里需要请求一下前置接口数据
                    logging.debug("初始化获取case_data：{}".format(case_data))
                else:

                    # 处理前置接口测试信息
                    # pre_test_info = replaceRelevance.replace(pre_test_info, __relevance)
                    logging.debug("测试信息处理结果：{}".format(pre_test_info))
                    # 处理前置接口Cookies
                    if pre_test_info['cookies']:
                        cookies = aconfig[PROJECT_NAME]['cookies']
                        logging.debug("请求Cookies处理结果：{}".format(cookies))

                    # 处理前置接口入参：获取入参-替换关联值-发送请求
                    pre_parameter = read_json(pre_case_data['summary'], pre_case_data['parameter'], pre_case_path)
                    # pre_parameter = replaceRelevance.replace(pre_parameter, __relevance)
                    pre_case_data['parameter'] = pre_parameter
                    logging.debug("请求参数处理结果：{}".format(pre_parameter))
                    logging.info("执行前置接口测试用例：{}".format(pre_test_info))
                    code, data = apiSend.send_request(pre_test_info, pre_case_data, case_path)
                    # 检查接口是否调用成功
                    if data:
                        # 处理当前接口入参：获取入参-获取关联值-替换关联值
                        var = {}
                        _values = readRelevance.getvalue(data, v, [])
                        print("_values:",_values)# 获取前置条件中指定的key值对应的value列表
                        if '[' in str(va):
                            n = int(str(va).split('[')[1].replace(']','').replace(" ", ""))
                            if str(n) + ']}' in str(case_data['parameter']):
                                var[va] = _values[n]
                            else:
                                var[v] = _values[n]
                        else:
                            var[v] = _values[0]  # 取第一个最早出现的字段
                        logging.debug("获取关键字var：{}".format(var))
                        # parameter = read_json(case_data['summary'], case_data['parameter'], post_case_yaml)
                        parameter = case_data['parameter']
                        case_data['parameter'] = replaceRelevance.replace_relevance_new(parameter, var)
                        body = case_data['check_body']['expected_result']
                        if '${' in str(body):
                            case_data['check_body']['expected_result'] = replaceRelevance.replace_relevance_new(
                            case_data['check_body']['expected_result'], var)
                    else:
                        time.sleep(1)
                        logging.error("前置接口请求失败！等待1秒后重试！")
            else:
                pre_case_yaml = PAGE_DIR + "/" + str(k)
                pre_case_path = os.path.dirname(pre_case_yaml)
                pre_case_dict = readYaml.read_yaml_data(pre_case_yaml)
                pre_test_info = pre_case_dict['test_info']
                pre_case_data = pre_case_dict['test_case'][0]
                if RC['case_switch'] == 0:  # 用例运行模式为场景用例不单独立执行前置
                    pre_path_list = [i for i in pre_case_yaml.replace('\\','/').split('/') if i != '' and '.yaml' not in i]
                    case_path_list = [i for i in case_path.split('/') if i != '' and '.yaml' not in i]
                    if pre_path_list == case_path_list:  # 对比前置条件用例路径与本用例路径是否在同一目录下
                        pre_file_path = pre_case_yaml
                    else:
                        _pre_path, f = os.path.split(case_path)
                        pre_path = '/'.join(_pre_path.split('/').pop())
                        pre_file_path = os.path.join(pre_path, pre_case_path+'/'+str(k))
                    # 从缓存的前置接口返回值中替换变量
                    my_data = init_premise_from_cache_new(case_data, pre_file_path, va, k)
                    if not my_data:
                        pre_test_info, pre_case_data = init_premise_new(pre_test_info, pre_case_data, pre_file_path)
                        code, data = apiSend.send_request(pre_test_info, pre_case_data, pre_file_path)
                        # test_info, case_data = init_premise_new(test_info, case_data, case_path)
                        if data:
                            for v in va:
                            # 处理当前接口入参：获取入参-获取关联值-替换关联值
                                if '[' in str(v):
                                    i = str(v).split('[')[0]
                                else:
                                    i = v
                                var = {}
                                _values = readRelevance.getvalue(data, i, [])
                                if '[' in str(v):
                                    n = int(str(v).split('[')[1].replace(']', '').replace(" ", ""))
                                    var[v] = _values[n]
                                else:
                                    var[v] = _values[0]  # 取第一个最早出现的字段
                                # print("_values:", _values)  # 获取前置条件中指定的key值对应的value列表
                                # var[i] = _values[0]  # 取第一个最早出现的字段
                                logging.debug("获取关键字var：{}".format(var))
                                case_data['parameter'] = replaceRelevance.replace_relevance_new(case_data['parameter'], var)
                                body = case_data['check_body']['expected_result']
                                if '${' in str(body):
                                    case_data['check_body']['expected_result'] = replaceRelevance.replace_relevance_new(
                                        case_data['check_body']['expected_result'], var)
                    else:
                        case_data = my_data
    else:
        # 处理当前接口入参：获取入参-获取关联值-替换关联值
        if case_data['parameter'] == False:
            case_data['parameter'] = None
        else:
            parameter = read_json(case_data['summary'], case_data['parameter'], case_path)
            # parameter = replaceRelevance.replace(parameter, __relevance)
            case_data['parameter'] = parameter
            logging.debug("请求参数处理结果：{}".format(parameter))

        # 获取当前接口期望结果：获取期望结果-获取关联值-替换关联值
        if case_data['check_body']['check_type'] == "check_string":
            expected_rs = str(case_data['check_body']['expected_result'])
            case_data['check_body']['expected_result'] = expected_rs
            logging.debug("期望返回处理结果：{}".format(expected_rs))
        elif case_data['check_body']['check_type'] == "check_not_in":
            expected_rs = str(case_data['check_body']['expected_result'])
            case_data['check_body']['expected_result'] = expected_rs
            logging.debug("期望返回处理结果：{}".format(expected_rs))
        else:
            expected_rs = read_json(case_data['summary'], case_data['check_body']['expected_result'], case_path)
            # __relevance = readRelevance.get_relevance(parameter, expected_rs, __relevance)
            # expected_rs = replaceRelevance.replace(expected_rs, __relevance)
            case_data['check_body']['expected_result'] = expected_rs
            # logging.clueCheck("期望返回处理结果：{}".format(case_data))
    test_info, case_data = evn_var_replace(test_info, case_data)
    case_data = random_param_replace(case_data)
    case_data = getParamToken(case_data)
    return test_info, case_data


def getParamToken(case_data):
    '''
    :param case_data: 入参中有鉴权逻辑需要自己在authentication.py文件中写，再在入参中引入里面的方法
    :return:
    '''
    if case_data["parameter"] != None:
        if 'def' in str(case_data["parameter"]):
            for k,v in case_data["parameter"].items():
                if isinstance(v,dict):
                    if 'def' in v.keys():
                        if '(' in v["def"]:
                            run_evn = RC["run_evn"]
                            r = v["def"].strip(' ')
                            obj = str(r).split("(")[0]
                            parm = str(r).split("(")[1]
                            parm = parm.replace('evn',run_evn).replace('EVN',run_evn).replace(')','')
                            case_data["parameter"][k] = getattr(authentication, obj, None)(parm)
                        else:
                            _def = getattr(authentication, v["def"], None)
                            case_data["parameter"][k] = _def()

    return case_data


def random_param_replace(case_data):
    """
    替换参数中的随机数，方法在randomly.py
    """
    parameter = case_data["parameter"]
    body = case_data["check_body"]["expected_result"]
    pattern = re.compile(r'random[\[](.*?)[]]', re.S)
    if "random[" in str(parameter):
        var_list = re.findall(pattern, str(parameter))
        for var in var_list:
            _def = getattr(randomly, var, None)
            randomdata = _def()
            parameter = str(parameter).replace("random[{}]".format(var),str(randomdata))
        case_data["parameter"] = ast.literal_eval(parameter)
    if "random[" in str(body):
        for var in var_list:
            _def = getattr(randomly, var, None)
            randomdata = _def()
            body = str(body).replace("random[{}]".format(var),str(randomdata))
        case_data["check_body"]["expected_result"] = ast.literal_eval(body)
    return case_data


def premise_path(premise_file,case_path):
    """
    return: 判断前置上脚本路径是否存在，是否写的yaml文件，若不存在则在同路径下查询文件
    """
    if ".yaml" not in premise_file:
        premise_path = premise_file + ".yaml"
    else:
        premise_path = premise_file
    if os.path.exists(os.path.join(PAGE_DIR,premise_path)):
        return premise_path
    else:
        _dir = str(os.path.dirname(case_path)).split("page")
        if len(_dir) != 0:
            case_dir = _dir[1]
        else:
            case_dir = "page"
        premise_path = os.path.join(case_dir,premise_path)
        return premise_path


def evn_var_replace(test_info, case_data):
    '''
    :param test_info:
    :param case_data:
    :return: 替换环境变量
    '''
    aconfig = readYaml.read_yaml_data(API_CONFIG)
    evnconfig = readYaml.read_yaml_data(EVN_CONFIG)
    evn_info = evnconfig[PROJECT_NAME]
    run_evn = RC["run_evn"]
    project_info = aconfig[PROJECT_NAME][run_evn]
    evnlist = jsonpath.jsonpath(project_info,"$..evn")

    if evnlist == False:
        logging.debug("项目中apiconfig文件未配置环境变量")
        return test_info, case_data
    else:
        _evn = evnlist[0]
        evn_var = evn_info[_evn]
        address =  test_info["address"]
        if "evn[" in address:
            pattern = re.compile(r'evn[\[](.*?)[]]', re.S)
            var_list = re.findall(pattern, address)
            for var in var_list:
                address = str(address).replace("evn[{}]".format(var), evn_var[var])
            test_info["address"] = address
        parameter = case_data["parameter"]
        if "evn[" in str(parameter):
            pattern = re.compile(r'evn[\[](.*?)[]]', re.S)
            var_list = re.findall(pattern, str(parameter))
            for var in var_list:
                parameter = str(parameter).replace("evn[{}]".format(var), evn_var[var])
            case_data["parameter"] = ast.literal_eval(parameter)
        result = case_data["check_body"]
        if "evn[" in str(result):
            pattern = re.compile(r'evn[\[](.*?)[]]', re.S)
            var_list = re.findall(pattern, str(result))
            for var in var_list:
                result = str(result).replace("evn[{}]".format(var), evn_var[var])
            case_data["check_body"] = ast.literal_eval(result)
        return test_info, case_data


def return_postposition(test_info, case_data,case_yaml):
    """用例后置条件执行，提取关键值
    :param test_info: 测试信息
    :param case_data: 用例数据
    :return:
    """
    # 获取项目公共关联值
    if RC['case_switch'] == 0:
        return

    aconfig = readYaml.read_yaml_data(API_CONFIG)
    run_evn = RC["run_evn"]
    __relevance = aconfig[PROJECT_NAME][run_evn]
    # 处理Cookies
    if test_info['cookies']:
        cookies = aconfig[PROJECT_NAME]['cookies']
        logging.debug("请求Cookies处理结果：{}".format(cookies))

    # 判断是否存在后置还原接口
    post_case_path = test_info["postposition"]
    if post_case_path:
        # 获取后置接口用例
        for _k,_v in post_case_path.items():
            logging.info("已获取后置还原接口测试用例：{}".format(post_case_path))
            post_case_yaml = PAGE_DIR + _k
            post_case_path = os.path.dirname(post_case_yaml)
            post_case_dict = readYaml.read_yaml_data(post_case_yaml)
            post_test_info = post_case_dict['test_info']
            post_case_data = post_case_dict['test_case'][0]
            if _v != 'false':
                data = cache.get(case_yaml)
                var = {}
                _values = readRelevance.getvalue(data, _v, [])  # 获取前置条件中指定的key值对应的value列表
                var[_v] = _values[0]  # 取第一个最早出现的字段
                if '${' in post_test_info["address"]:
                    post_test_info["address"] = str(post_test_info["address"]).replace("${"+_v +"}",var[_v])
                post_case_data["parameter"][_v] = var[_v]
                code, data = apiSend.send_request(post_test_info, post_case_data, post_case_yaml)
            else:
                if post_test_info['premise']:  # 这里可以考虑做递归
                    logging.info("后置还原接口中特么还有前置接口测试用例：{}".format(post_test_info['premise']))
                    for _key,_value in post_test_info['premise'].items():
                        pre_post_case_yaml = PAGE_DIR + _key
                        if cache.get(pre_post_case_yaml):
                            post_case_data = init_premise_from_cache_new(post_case_data, pre_post_case_yaml, _value, _key)
                            case_data = post_case_data
                            code, data = apiSend.send_request(post_test_info, case_data, post_case_yaml)
                        else:
                            _test_info,_case_data = init_premise_new(post_test_info,post_case_data,post_case_yaml)
                            logging.info("_test_info：{}".format(_test_info))
                            code, data = apiSend.send_request(_test_info,_case_data, post_case_yaml)
                else:
                    code, data = apiSend.send_request(post_test_info, post_case_data, post_case_yaml)
    else:

        # 处理当前接口入参：获取入参-获取关联值-替换关联值
        logging.debug("后置还原接口没有指定接口")
        return

    return test_info, case_data


def get_related_data(post_case_path):
    '''
    case_name: 用例路径
    retrun: 后置用例返回值
    fucation:递归后置用例结果
    '''
    logging.info("获取后置还原接口测试用例：{}".format(post_case_path))
    post_case_yaml = PAGE_DIR + post_case_path
    res_data = cache.get(post_case_yaml)
    if res_data:
        return res_data
    else:
        post_case_dict = readYaml.read_yaml_data(post_case_yaml)
        post_test_info = post_case_dict['test_info']
        post_pre_case_yaml = PAGE_DIR + post_test_info['premise']
        post_case_data = post_case_dict['test_case'][0]
        if post_pre_case_yaml:
            get_related_data(post_pre_case_yaml)
            test_info, test_case = init_premise(post_test_info, post_case_data, post_case_yaml)
            code, res_data = send_request(test_info, test_case, post_case_yaml)
        else:
            code, res_data = apiSend.send_request(post_test_info, post_case_data)
    return res_data


def init_premise_from_cache(case_data, case_path, post_case_yaml, __relevance):
    data = cache.get(str(post_case_yaml).replace("\\", "/"))
    logging.debug("再次从缓存中{} 获取到数据：{}".format(post_case_yaml, data))
    if not isinstance(data, dict):
        data = json.loads(data)
    logging.debug("data type::{}".format(type(data)))
    logging.debug("从前置接口请求缓存数据中获取返回值：{}".format(data))
    if data:
        if case_data['parameter']:
            parameter = read_json(case_data['summary'], case_data['parameter'], post_case_yaml)
            __relevance = readRelevance.get_relevance(data, parameter, __relevance)
            parameter = replaceRelevance.replace(parameter, __relevance)
            case_data['parameter'] = parameter
            logging.debug("缓存接口请求参数处理结果：{}".format(parameter))
        else:
            case_data['parameter'] = None
        return case_data
    else:
        return data


def init_premise_from_cache_new(case_data, case_path,va, k):
    '''
    _key:前置条件中的需要获取的字段key值
    '''

    PATH = str(case_path).replace("\\", "/")
    if PAGE_DIR not in PATH:
        PATH = PAGE_DIR + PATH
    data = cache.get(PATH)  # 获取用例文件名对应的接口的返回值（之前存在缓存中）
    L = cache.keys()
    logging.debug("再次从缓存中{} 获取到数据：{},{}".format(PATH, data, L))
    if data == None:
        if cache.has(str(PATH).replace("\\", "/")):
            logging.debug("缓存中{} 获取到数据为空：{}".format(PATH, data))
            return None
        else:
            return False
    if not isinstance(data, dict):
        data = json.loads(data)
    logging.debug("data type::{}".format(type(data)))
    logging.debug("从前置接口请求缓存数据中获取返回值new：{}".format(data))
    if data:
        if case_data['parameter']:
            if not isinstance(va,list):
                if '[' in str(va):
                    _key = str(va).split('[')[0]
                else:
                    _key = va
                try:

                    var = {}
                    _values = readRelevance.getvalue(data,_key,[]) #获取前置条件中指定的key值对应的value列表
                    if '[' in str(va):
                        n = int(str(va).split('[')[1].replace(']','').replace(" ", ""))
                        if str(n)+']}' in str(case_data['parameter']):
                            var[va] = _values[n]
                        else:
                            var[_key] = _values[n]
                    else:
                        var[_key] = _values[0]  # 取第一个最早出现的字段
                    # var[_key]=_values[0] #取第一个最早出现的字段
                    case_data['parameter'] = replaceRelevance.replace_relevance_new(case_data['parameter'], var, k) #将入参中的变量替换成前置条件中的字段
                    logging.debug("缓存接口请求参数处理结果2：{}".format(case_data['parameter']))
                    body = case_data['check_body']['expected_result']
                    if '${' in str(body):
                        case_data['check_body']['expected_result'] = replaceRelevance.replace_relevance_new(case_data['check_body']['expected_result'], var)
                except:
                    logging.error("前置条件中没有找到对应的字段：{}".format(_key))
                logging.info("缓存接口请求参数case_data2：{}".format(case_data))
                return case_data
            else:
                for _key in va:
                    if '[' in str(_key):
                        key = str(_key).split('[')[0]
                    else:
                        key = _key
                    try:
                        var = {}
                        _values = readRelevance.getvalue(data, key, [])  # 获取前置条件中指定的key值对应的value列表
                        if '[' in str(_key):
                            n = int(str(_key).split('[')[1].replace(']','').replace(" ", ""))
                            var[_key] = _values[n]
                        else:
                            var[_key] = _values[0]  # 取第一个最早出现的字段
                        # var[key] = _values[0]  # 取第一个最早出现的字段
                        case_data['parameter'] = replaceRelevance.replace_relevance_new(case_data['parameter'], var, k)  # 将入参中的变量替换成前置条件中的字段
                        logging.debug("缓存接口请求参数处理结果1：{}".format(case_data['parameter']))
                        body = case_data['check_body']['expected_result']
                        if '${' in str(body):
                            case_data['check_body']['expected_result'] = replaceRelevance.replace_relevance_new(
                            case_data['check_body']['expected_result'], var)
                    except:
                        logging.error("前置条件中没有找到对应的字段：{}".format(key))
                return case_data
    else:
        return data

